<script setup>
import { ref, computed, watch } from 'vue'
import BaseRankingChart from '@/components/chart/BaseRankingChart.vue'
import CustomDateRadio from '@/components/header/CustomDateRadio.vue'
import { useAreaStore } from '@/stores/area'
import { getAreaReportApi } from '@/api/area'
import { handleError } from '@/utils/handleError'

const props = defineProps({
    title: {
        type: String,
        default: '区域用电排名'
    },
    height: {
        type: String,
        default: '230px'
    }
})

const areaStore = useAreaStore()
const rankingChartTime = ref(null)
const rankingChartData = ref([])
const rankingChartLoading = ref(false)

// 监听公司变化，重新获取区域数据
watch(() => areaStore.areas, () => {
    if (rankingChartTime.value) {
        getAreaRankingData()
    }
}, { deep: true })

// 获取区域排名数据
async function getAreaRankingData() {
    if (!rankingChartTime.value) return

    rankingChartLoading.value = true
    try {
        let tempData = []
        for (const area of areaStore.areas) {
            let res = await getAreaReportApi({
                id: area.id,
                start_time: rankingChartTime.value.start_time,
                end_time: rankingChartTime.value.end_time,
                type: 2  // 用电类型
            })

            if (res?.aggregated_data) {
                const value = res.aggregated_data
                    .filter((item) => Array.isArray(item) && item.length > 0)
                    .reduce((acc, cur) => {
                        return acc + cur.reduce((sum, meter) => {
                            const used = meter && typeof meter.Used !== 'undefined' ? Number(meter.Used) : 0;
                            return sum + used;
                        }, 0);
                    }, 0);

                if (value > 0) {
                    tempData.push({
                        name: area.name,
                        value: Number(value),
                        area: area.id
                    });
                }
            }
        }

        rankingChartData.value = tempData.sort((a, b) => b.value - a.value);
    } catch (error) {
        handleError(error, '获取区域用电排名数据失败')
        rankingChartData.value = []
    } finally {
        rankingChartLoading.value = false
    }
}

// 监听时间变化
watch(() => rankingChartTime.value, getAreaRankingData, { immediate: true })
</script>

<template>
    <div class="card-header">
        <span>{{ title }}</span>
        <CustomDateRadio @update:modelValue="rankingChartTime = $event"></CustomDateRadio>
    </div>
    <BaseRankingChart :title="title" :data="rankingChartData" :height="height" />
</template>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}
</style>